//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	SqlQueryBuilderOrderBy.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System.Linq;

namespace Smart.Common.Entities
{
	/// <summary>
	/// OrderBy group
	/// </summary>
	public class SqlQueryBuilderOrderBy<TExecutorType> : SqlQueryBuilderItemGroup<TExecutorType>, IQueryBuilderOrderBy<TExecutorType>
		where TExecutorType : class
	{
		public SqlQueryBuilderOrderBy()
			: base("ORDER BY")
		{
		}

		/// <summary>
		/// Create group
		/// </summary>
		public override SqlQueryBuilderItemGroup<TExecutorType> Create()
		{
			return new SqlQueryBuilderOrderBy<TExecutorType> { Group = this, Query = Query };
		}

		/// <summary>
		/// Add sort by <paramref name="field"/> ascending
		/// </summary>
		public IQueryBuilderOrderBy<TExecutorType> Asc(string field)
		{
			AddItem(new SqlQueryBuilderOrderItem<TExecutorType>(field, "ASC"));

			return this;
		}

		/// <summary>
		/// Add sort by <paramref name="field"/> descending
		/// </summary>
		public IQueryBuilderOrderBy<TExecutorType> Desc(string field)
		{
			AddItem(new SqlQueryBuilderOrderItem<TExecutorType>(field, "DESC"));

			return this;
		}

		/// <summary>
		/// Add sort by <paramref name="field"/> with <paramref name="asc"/>
		/// </summary>
		public IQueryBuilderOrderBy<TExecutorType> Sort(string field, bool asc)
		{
			AddItem(new SqlQueryBuilderOrderItem<TExecutorType>(field, (asc ? "ASC" : "DESC")));

			return this;
		}

		/// <summary>
		/// Format QueryBuilder statement
		/// </summary>
		public override string FormatQuery()
		{
			var items = Children.Where(item => item != null);

			var filters = items.CastToString(", ", item => item.FormatQuery());

			return filters.IsNullOrEmpty() ? string.Empty : Op + " " + filters;
		}
	}
}